#!/bin/bash
#
# Luiz Flavio Rojo Fernandes (lrojo@uoldiveo.com)
# 
# Script de envio de email automatico com a audiencia da Folha
# 

# Declara variaveis
AWK=$(which awk)
DATE=$(which date)
GREP=$(which grep)
OPENSSL=$(which openssl)
PRINTF=$(which printf)
SED=$(which sed)
MKTEMP=$(which mktemp)
UNAME=$(which uname)
CAT=$(which cat)
# Verifica o binario do mail

if [ -f /usr/bin/mailx ]
then
    MAIL="/usr/bin/mailx"
else
    MAIL=$(which mail)
fi

# Faz a consulta no banco

STDOUT_IPHONE=/var/tmp/audiencia_folha_iphone
STDOUT_WEB=/var/tmp/audiencia_folha_web
STDOUT_TMP=/var/tmp/audiencia_folha

DATA=`date --date='1 day ago' +%Y-%m-%d`
mysql -t -u root -e "select * from streams where stream_name like 'eventos3_flash.sdp' and event_date = '$DATA' \G" streaming_logs > $STDOUT_IPHONE
mysql -t -u root -e "select * from streams where stream_name like 'eventos3_iphone.sdp' and event_date = '$DATA' \G" streaming_logs > $STDOUT_WEB

NAME_I="$( ${CAT} ${STDOUT_IPHONE} | grep "stream_name:" | awk {'print $2'} )"
UNIQ_VISITORS_I="$( ${CAT} ${STDOUT_IPHONE} | grep "uniq_visitors:" | awk {'print $2'} )"
VISITORS_I="$( ${CAT} ${STDOUT_IPHONE} | grep "visitors:" | grep -v _ | awk {'print $2'} )"
AVG_TIME_I="$( ${CAT} ${STDOUT_IPHONE} | grep "sessions_time_avg:" | awk {'print $2'} )"
SIM_VISITORS_I="$( ${CAT} ${STDOUT_IPHONE} | grep "max_concurrent_visitors:" | awk {'print $2'} )"
DATE_I="$( ${CAT} ${STDOUT_IPHONE} | grep "event_date:" | awk {'print $2'} )"

NAME_W="$( ${CAT} ${STDOUT_WEB} | grep "stream_name:" | awk {'print $2'} )"
UNIQ_VISITORS_W="$( ${CAT} ${STDOUT_WEB} | grep "uniq_visitors:" | awk {'print $2'} )"
VISITORS_W="$( ${CAT} ${STDOUT_WEB} | grep "visitors:" | grep -v _ | awk {'print $2'} )"
AVG_TIME_W="$( ${CAT} ${STDOUT_WEB} | grep "sessions_time_avg:" | awk {'print $2'} )"
SIM_VISITORS_W="$( ${CAT} ${STDOUT_WEB} | grep "max_concurrent_visitors:" | awk {'print $2'} )"
DATE_W="$( ${CAT} ${STDOUT_WEB} | grep "event_date:" | awk {'print $2'} )"

# Variáveis de composição da mensagem


ADMIN="l-tec-alta-audiencia@uolinc.com;melina.paula@grupofolha.com.br"
DATE_CUR="$(${DATE} +'%d/%m/%Y as %H:%M')"
SRV=$(${UNAME} -n)

SUBJECT="Audiencia de Streamings da folha"
RESULT="${SUBJECT}"
STDOUT="$( cat ${STDOUT_TMP} )"

${MAIL} -s "[${SRV}]: ${SUBJECT}" -u cronroot ${ADMIN} <<- EOM 
        
E-mail automatico enviado pelo servidor ${SRV}.

${RESULT}

Nome: ${NAME_I}
Usuarios Unicos: ${UNIQ_VISITORS_I}
Total Usuarios: ${VISITORS_I}
Tempo medio: ${AVG_TIME_I}
Usuarios Simultanios: ${SIM_VISITORS_I}
Data: ${DATE_I}

Nome: ${NAME_W}
Usuarios Unicos: ${UNIQ_VISITORS_W}
Total Usuarios: ${VISITORS_W}
Tempo medio: ${AVG_TIME_W}
Usuarios Simultanios: ${SIM_VISITORS_W}
Data: ${DATE_W}

Script:                         $0
Execucao:                       ${DATE_CUR}
Informarcoes:                   <l-tec-alta-audiencia@uolinc.com>"

EOM
